from flask import Flask, render_template,request,jsonify,redirect,send_from_directory
#from base.loggers import getLogHanderTime,getLogHandlerFile
import logging,os,json

app = Flask(__name__)

app.logger.disabled = True
werkzeug_logger = logging.getLogger('werkzeug')
werkzeug_logger.disabled = True

check = {}
for line in os.popen("cat ./pdf/popular.txt ./pdf/rest.txt ./pdf/latest.txt").read().strip().split("\n"):
    if '\t' not in line: continue
    num, title = line.split("\t")
    check[title.replace("/","|").strip().replace(" ","_")] = int(num.strip())
    
@app.route('/book/<string:title>')
def book(title):
    num = check[title]
    data = json.loads(open("./pdf/output_%d.json"%(num),"r").read().strip())
    for i,line in enumerate(open("./pdf/output_%d.txt"%(num),"r")):
        if i == 0: data['author'] = line.strip()
        if i == 1: data['title'] = line.strip()
        if i == 2: data['lang'] = line.strip()
    if isinstance(data['Synopsis'], list) == False: data['Synopsis'] = [data['Synopsis']]
    if isinstance(data['Genres'], list) == False: data['Genres'] = data['Genres'].replace(", ",",").split(",")
    data['pdf'] = '/pdf/%s.pdf'%(title)
    data['Genres'] = ", ".join(data['Genres'])
    return render_template('book.html',data=data)

@app.route('/')
def index0():
    info = data('popular',1)
    return render_template('test.html',category='popular',title='Popular', totalnum=info['totalPages'], pagenum=info['page'], data=info['data'], itemsPerPage=info['itemsPerPage'])

@app.route('/<string:category>/<int:page>')
def index(category='popular',page=1):
    if category not in ['popular','latest'] and category.startswith('alpha') == False: return "Opps! Segmentation fault (core dumped). "
    if category == 'alpha-a': title = 'Alpha: A-E'
    elif category == 'alpha-f': title = 'Alpha: F-J'
    elif category == 'alpha-k': title = 'Alpha: K-O'
    elif category == 'alpha-p': title = 'Alpha: P-T'
    elif category == 'alpha-u': title = 'Alpha: U-Z'
    else: title = category[:1].upper() + category[1:]
    info = data(category,page)
    return render_template('test.html',category=category,title=title, totalnum=info['totalPages'], pagenum=info['page'], data=info['data'], itemsPerPage=info['itemsPerPage'])

def data(cate,page):
    books = []
    for line in open('./pdf/'+cate+'.txt',"r"):
        num,title = line.strip().split("\t")
        title_updated = title.replace("/","|").replace(" ","_")
        num = int(num)
        result = {}
        if os.path.exists("./pdf/output_%d.txt"%(num)) == False or os.path.exists("./static/pdf/%s.pdf"%(title_updated)) == False: continue
        cont = open("./pdf/output_%d.txt"%(num),"r").read().split("\n")
        result['pdf'] = '/book/%s'%(title_updated)
        result['title'] = cont[1]
        result['author'] = cont[0]
        result['lang'] = cont[2]
        books.append(result)

    items_per_page = 20
    start_index = (page - 1) * items_per_page
    end_index = start_index + items_per_page
    paginated_books = books[start_index:end_index]
    response = {
        "data": paginated_books,
        "page": page,
        "itemsPerPage": items_per_page,
        "totalItems": len(books),
        "totalPages": (len(books) + items_per_page - 1) // items_per_page
    }
    return response

@app.route('/pdf/<string:pdf>')
def download_pdf(pdf):
    return send_from_directory('./static/pdf',pdf)

@app.route('/robots.txt')
def robots_txt():
    return send_from_directory('./','robots.txt')

if __name__ == '__main__':
    #serve(app, host='0.0.0.0', port=80)    
    app.run(host='127.0.0.1', port=5001, debug=False, use_reloader=False)

